<?php
include 'readDB.php';
include 'checks.php';
$entidad=$_GET['object'];
$params = $_GET['params'];
$order = $_GET['order'];
$paramsObj = json_decode($params,true);
$msj="";

$results=array();
if (isset($entidades[$entidad])){ //CHEQUEA SI LA ENTIDAD EXISTE
	$checkFields=checkFields($entidades[$entidad],$paramsObj);
	if ($checkFields==""){
			$query=makeLoadQuery($entidades[$entidad],$paramsObj,$entidad,$order);
			if (strlen($query)>2){
// 				echo $query;
				$res=mysql_query($query) or die("ERROR");
				while ($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
	 			  	//print_r($row);
					array_push($results, $row);
				}
				$rowCount = mysql_num_rows($res);
				$ok=true;				
			}else{
				$msj= "Operator '" . $query . "' not recognized ";
				$ok=false;				
			}
	}else{
			$msj= "Field " . $checkFields . " not exists for object " .  $entidad;
			$ok=false;
	}
}else{
		$msj= "Object " . $entidad . "not exists";
		$ok=false;
}

$ret=array("ok" => $ok,"msj" => $msj,"rows" => $results, "rowCount" => $rowCount);
echo json_encode($ret);

function makeLoadQuery($entidad,$pars,$object,$order){
	$operators=array("GT" => " > ","LT" => " < ","GE" => " >= ","LE" => " <= ");
	$pre="SELECT * FROM " . $object;    
    $post="";    
	$keys=array_keys($pars);
	$out="";	
	for ($x=0;$x<count($keys);$x++){
		$fieldName=$entidad[$keys[$x]]["name"];
		$fieldValue=$pars[$fieldName];		
		$stringB=(strstr($entidad[$keys[$x]]["type"], 'varchar')!=""); // SI ES VARCHAR
		$dateB=(strstr($entidad[$keys[$x]]["type"], 'date')!=""); // SI ES DATE
		$comparator="";
		if ($stringB){
			$fieldValue= "'%" . $fieldValue . "%'";
			$comparator=" LIKE ";
		}else{
			$comparator="=";
		}
		
		if ($dateB){
			$fieldValue= "'%" . $fieldValue . "%'";
		}
		
		if (is_array($fieldValue)){
			if ($fieldValue[0]=="BT"){
				$post=$post . $fieldName . " > " . $fieldValue[1] . " AND " . $fieldName . " < " . $fieldValue[2];
			}else if ($fieldValue[0]=="IN"){
				$post=$post . $fieldName . " IN (";
				for ($i=1;$i<count($fieldValue);$i++){
					$post=$post . $fieldValue[$i];
					if ($i+1<count($fieldValue)){
						$post = $post . ',';
					}else{
						$post = $post . ')';
					}
				}
			}else{
				if ($operators[$fieldValue[0]]!=""){
					$post=$post . $fieldName . $operators[$fieldValue[0]] . $fieldValue[1];								
				}else{
					return $fieldValue[0];
				}
			}
		}else{
			$post=$post . $fieldName . $comparator . $fieldValue;
		}
		if ($x+1<count($keys)){
			$post = $post . ' AND ';
		}
	}
	if ($post!=""){		
		$out= $pre  . " WHERE " . $post;		
	}else{
		$out= $pre;	
	}
	if ($order!=""){
		return $out . " ORDER BY " . $order; 
	}else{
		return $out;
	}
	
}

?>